package com.smile.frame.springbootsatoken.config;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SpringMVCUtil {
    private SpringMVCUtil() {
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            try {
                throw new Exception("非 web 上下文无法获取 HttpServletRequest");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return servletRequestAttributes.getRequest();
        }
    }

    public static HttpServletResponse getResponse(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            try {
                throw new Exception("非 web 上下文无法获取 HttpServletResponse");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return servletRequestAttributes.getResponse();
        }
    }
}